package com.delicious.system.controller;

import com.delicious.core.base.BaseResponse;
import com.delicious.system.service.AuthService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@RestController
@Slf4j
@AllArgsConstructor
public class AuthController {
    private final AuthService authService;

    /**
     * 登录，登录成功会返回Token给用户
     */
    @PostMapping(value = "/auth/login")
    public BaseResponse<String> login(String username, String password) throws AuthenticationException {
        return BaseResponse.of(authService.login(username, password));
    }

    @PostMapping(value = "/user/hi")
    public BaseResponse<String> userHi(String name) throws AuthenticationException {
        return BaseResponse.of("hi " + name + " , you have 'user' role");
    }

    @PostMapping(value = "/admin/hi")
    public BaseResponse<String> adminHi(String name) throws AuthenticationException {
        return BaseResponse.of("hi " + name + " , you have 'admin' role");
    }

    /**
     * 获取用户所拥有的权限列表
     * @return
     */
    @GetMapping(value = "/getAuthentication")
    public List<String> getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> list = new ArrayList<>();
        for (GrantedAuthority grantedAuthority : authorities) {
            log.info("权限列表：{}", grantedAuthority.getAuthority());
            list.add(grantedAuthority.getAuthority());
        }
        return list;
    }
}
